package com.example.smartvillage.utils;

import android.os.Handler;
import android.util.Log;

import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.concurrent.Executor;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class News {

    private static final String TAG = "新闻API";
    private final Handler resultHandler;
    private final Executor executor;
    private final NewsApi newsApi;

    public News(Executor executor, Handler resultHandler) {
        this.executor = executor;
        this.resultHandler = resultHandler;

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://v.juhe.cn/toutiao/")//基础URL
                .addConverterFactory(GsonConverterFactory.create()) //使用GsonConverterFactory，则可转化为JsonObject
                .build();

        //获得NewsApi实例
        this.newsApi = retrofit.create(NewsApi.class);
    }

    public void GetNewsList(String type, int page, int page_size, Callback<JsonObject> callback) {

        Call<JsonObject> call = newsApi.GetNewsList(type, page, page_size);

        executor.execute(() -> {
            try {
                Log.d(TAG, "查询新闻的线程："+Thread.currentThread().getName());
                Response<JsonObject> response = call.execute();//实际的网络请求
                Log.d(TAG, "获取新闻列表：返回的信息"+response.body());
                notifyResult(response, callback);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }

    public interface Callback<T> {
        /**
         * @param response Api调用结果
         */
        void onComplete(Response<T> response);
    }

    private void notifyResult(final Response<JsonObject> response, final Callback<JsonObject> callback) {
        resultHandler.post(() -> callback.onComplete(response));
    }

}

